package com.hairy.nipples.sound;

import static com.hairy.nipples.SmokeDetector.HANDLER;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import com.hairy.nipples.util.Logger;

public class BeepService extends Service {

	public static int RUN_AFTER_HOURS = 12; // default 12 hours
	public static boolean ENABLED = true; // default enabled

	private Timer timer;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Logger.debug("onStartCommand");
		if (ENABLED && (timer == null)) {
			Logger.debug("Restarting timer");
			initTimer(RUN_AFTER_HOURS, getBaseContext());
		}
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onCreate() {
		Logger.debug("onCreate");
		super.onCreate();
		initTimer(RUN_AFTER_HOURS, getBaseContext());

	}

	/**
	 * We are obfuscation wizards
	 */
	private void initTimer(int hours, final Context context) {
		Logger.debug("initing timer");
		timer = new Timer("HairyTimer");
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				Logger.debug("Timer task doing work");
				if (timer != null)
					timer.cancel();
				timer = null;
				if (ENABLED) {
					// PhoneMovementDetector.delegateActions(context,
					// new PhoneMovementBasedActionsCallback() {
					// @Override
					// public void doActionsWhenStill() {
					// Logger.debug("Phone is not moving. Safe to beep.");
					//
					initTimer(RUN_AFTER_HOURS, context);
					try {
						HANDLER.post(new Beeper());
					} catch (RuntimeException e) {
						e.printStackTrace();
						Logger.debug(e.getMessage());
					}
					Logger.debug("Beeper thread started");
					// }
					//
					// @Override
					// public void doActionsWhenMoving() {
					// Logger.debug("Phone is moving. Not beeping.");
					// initTimer(1, context); // init after 1 hour
					// }
					// });
				} else {
					Logger.debug("Nothing to do, 'cos I'm disabled");
				}
			}
		}, generateRandomMilliSeconds(hours));
	}

	private static int generateRandomMilliSeconds(int hours) {
		Random randomGenerator = new Random();
		// deviation is 20% of RUN_AFTER
		int randomDeviationInMinutes = randomGenerator
				.nextInt((int) (hours * 60 * 0.2D)) + 1;
		// minimum is 80%
		int runAfterInMinutes = (int) (hours * 60 * 0.8D);

		int resultInMinutes = (runAfterInMinutes + randomDeviationInMinutes);
		Logger.debug("Running after : " + resultInMinutes + " minutes");
		return resultInMinutes * 100; // 60*1000
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		timer.cancel();
		timer = null;
	}

}
